package com.ideal.gpt.app.local;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import com.lzwork.utility.file.FileOperation;
import com.lzwork.utility.file.FileUtility;
import com.lzwork.utility.file.LineContent;
import com.lzwork.utility.file.LineContent.LoadSetting;
import com.lzwork.utility.logger.LOGGER;

/**
 * @author LiZheng
 * @date 2023年9月4日 下午4:59:27
 */

public class TxtToWord
{
	public static int convertFolder(File folder, File outFolder, boolean log)
	{
		File[] files = folder.listFiles();
		int num = 0;

		for (File file : files)
		{
			boolean done = convertFile(file, outFolder, log);

			if (done)
				num++;
			else
				LOGGER.log(LOGGER.FILE, "Parse file fail: " + file.getName());
		}

		return num;
	}

	public static boolean convertFile(File file, File outFolder, boolean log)
	{
		LoadSetting setting = new LoadSetting();
		setting.setLogState(log);
		setting.setTrimSpace(false);
		List<String> content = LineContent.loadFile(file, setting);

		String name = FileUtility.getFileName(file) + ".docx";
		File output = FileUtility.getFileSafe(outFolder, name);
		FileOperation.validateFileContent(output, true);

		try (XWPFDocument xwpfDocument = new XWPFDocument(); FileOutputStream fileOutputStream = new FileOutputStream(output);)
		{
			for (String str : content)
			{
				XWPFParagraph para = xwpfDocument.createParagraph();
				XWPFRun run = para.createRun();
				run.setText(str);
			}

			xwpfDocument.write(fileOutputStream);
			fileOutputStream.close();
			LOGGER.log(LOGGER.FILE, "Save done: " + output.getName());
			return true;
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}

		return false;
	}

	public static void main(String[] args) throws IOException
	{
		File folderIn = new File("V:/doc qa/政策类知识信息数据-处理后/");
		File folderOut = new File("V:/doc qa/政策类知识信息数据_word/");

		int num = convertFolder(folderIn, folderOut, false);

		LOGGER.log(LOGGER.FILE, "Convert files: " + num);
	}
}
